<?php

namespace addons\workorder\model;

use think\Model;
use traits\model\SoftDelete;
use app\admin\model\workorder\Fields;

/**
 * 工程师模型
 */
class Orders extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'workorder_orders';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    protected $append = [
        'createtime_text'
    ];

    public function getCreatetimeTextAttr($value, $data)
    {
        return human_date($data['createtime']);
    }

    public static function getFields($values = null, $position = -1)
    {
        $where['status'] = 1;
        if ($position != -1) {
            $where['position'] = $position;
        }
        $fields = Fields::where($where)->order('weigh desc,id desc')->select();
        foreach ($fields as $v) {
            $v->value = isset($values[$v->name]) && $v->autofill ? $values[$v->name] : '';
            if (!$v->value) {
                $v->value = $v->default;
            }
            $v->unirule = trim($v->rule, ',') ? explode(',', trim($v->rule, ',')) : false;
            $v->rule    = str_replace(',', '; ', $v->rule);
            if (in_array($v->type_list, ['checkbox', 'lists', 'images'])) {
                $checked = '';
                if ($v['minimum'] && $v['maximum']) {
                    $checked = "{$v['minimum']}~{$v['maximum']}";
                } elseif ($v['minimum']) {
                    $checked = "{$v['minimum']}~";
                } elseif ($v['maximum']) {
                    $checked = "~{$v['maximum']}";
                }
                if ($checked) {
                    $v->rule .= (';checked(' . $checked . ')');
                }
            }
            if (in_array($v->type_list, ['checkbox', 'radio']) && stripos($v->rule, 'required') !== false) {
                $v->rule = str_replace('required', 'checked', $v->rule);
            }
            if (in_array($v->type_list, ['selects'])) {
                $v->extend .= (' ' . 'data-max-options="' . $v['maximum'] . '"');
            }
        }
        return $fields;
    }

    public function user()
    {
        return $this->hasOne('app\admin\model\User', 'id', 'user_id', [], 'LEFT')->setEagerlyType(0);
    }

    public function category()
    {
        return $this->hasOne('app\admin\model\workorder\Category', 'id', 'category_id', [], 'LEFT')->setEagerlyType(0);
    }

    public function urgentrank()
    {
        return $this->hasOne('app\admin\model\workorder\Urgentrank', 'id', 'urgency', [], 'LEFT')->setEagerlyType(0);
    }
}